from Crypto.Cipher import AES
from Crypto.Util.Padding import unpad
import socket
import os

# 密钥和初始化向量，需和客户端保持一致
key = b'Sixteen byte key'
iv = b'InitializationVe'

def aes_decrypt(encrypted_data):
    try:
        cipher = AES.new(key, AES.MODE_CBC, iv)
        decrypted_data = cipher.decrypt(encrypted_data)
        unpadded_data = unpad(decrypted_data, AES.block_size)
        return unpadded_data.decode('utf-8')
    except Exception as e:
        print(f"解密过程出错: {e}")
        return None


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('172.16.219.51', 8888)
log_file = 'server_log.txt'
client_socket = None

try:
    server_socket.bind(server_address)
    server_socket.listen(1)
    print(f'服务器正在监听 {server_address[0]}:{server_address[1]}')

    client_socket, client_address = server_socket.accept()
    print(f'接受来自 {client_address} 的连接')

    encrypted_data = client_socket.recv(4096)
    decrypted_data = aes_decrypt(encrypted_data)
    if decrypted_data is None:
        raise ValueError("解密失败，无法继续执行。")

    with open(log_file, 'w', encoding='utf-8') as log:
        log.write("接收到的加密内容:\n")
        log.write(encrypted_data.hex())
        log.write("\n\n解密后的内容:\n")
        log.write(decrypted_data)

    script_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(script_dir, 'received_file.txt')
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(decrypted_data)
    print('数据已解密并保存到 received_file.txt')

except OSError as e:
    print(f"服务器绑定或监听时出现错误: {e}")
except FileNotFoundError:
    print("文件未找到，请检查文件路径。")
except Exception as e:
    print(f"发生未知错误: {e}")
finally:
    if client_socket:
        client_socket.close()
    if server_socket:
        server_socket.close()
